package com.hj.controller;

import cn.hutool.core.util.StrUtil;
import com.hj.tools.TenCentCloudUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.Objects;

/**
 * @author hj
 * @Description 测试文件上传
 */
@Controller
@RequestMapping("/file")
public class TestFileController {

    private final Logger log= LoggerFactory.getLogger(TestFileController.class);

    private final TenCentCloudUtil tenCentCloudUtil;

    public TestFileController(TenCentCloudUtil tenCentCloudUtil) {
        this.tenCentCloudUtil = tenCentCloudUtil;
    }

    @PostMapping("/uploadFile")
    @ApiOperation(value = "上传文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件"),
            @ApiImplicitParam(name = "fileName", value = "名称")
    })
    @ResponseBody
    public void insertOrUpdateProductAttachment(MultipartFile file, String fileName) {
        System.out.println(fileName);
        String path = System.getProperty("user.dir") + "/";
        File f = new File(path, Objects.requireNonNull(file.getOriginalFilename()));
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), f);
            // 操作完上的文件 需要删除在根目录下生成的文件
            String cosPath = this.tenCentCloudUtil.cosUpload(f);
            log.debug("腾讯COS对象存储返回的路径:{}", cosPath);
            if (StrUtil.isNotBlank(cosPath)) {
                System.out.println(cosPath);
            }
            //删除文件测试
            tenCentCloudUtil.cosDelete(cosPath);
        } catch (IOException e) {
            log.error("multiFile转file类型出异常:{}", e.getMessage());
        }finally {
            boolean b=f.delete();
            System.out.println(b);
        }

    }


}
